package com.zjitc.bookshop39.entity;

import com.alibaba.fastjson.annotation.JSONField;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 登录用户实体类，实现Spring Security的UserDetails接口
 */
@Data
public class LoginUser implements UserDetails {

    // 用户实体
    private User user;
    
    // 权限列表
    private List<String> permissions;
    
    // 存储SpringSecurity所需的权限信息
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities != null){
            return authorities;
        }
        authorities = new ArrayList<>();
        for (String perm : permissions){
            authorities.add(new SimpleGrantedAuthority(perm));
        }
        return authorities;
    }

    public LoginUser() {
    }
    
    public LoginUser(User user, List<String> permissions) {
        this.user = user;
        this.permissions = permissions;
    }
    
    /**
     * 获取密码
     */
    @Override
    public String getPassword() {
        return user.getPassword();
    }

    /**
     * 获取用户名
     */
    @Override
    public String getUsername() {
        return user.getUsername();
    }

    /**
     * 账户是否未过期，默认返回true表示未过期
     */
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    /**
     * 账户是否未锁定，默认返回true表示未锁定
     */
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    /**
     * 凭证是否未过期，默认返回true表示未过期
     */
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    /**
     * 账户是否可用，默认返回true表示可用
     */
    @Override
    public boolean isEnabled() {
        return true;
    }
}

